Array.prototype.contains = function(item){
	return new RegExp("@@" + item + "@@").test("@@"+this.join("@@")+"@@");
};

MZ.VideoUtil = {};

/**
 * long类型转换为yyyy-mm-dd HH:mm:ss 日期格式
 */
MZ.VideoUtil.convertLongToDate = function(timesmap){
	if(timesmap.length == 13){
		timesmap = timesmap / 1000;
	}
	var time = new Date(timesmap);
	var month = parseInt(time.getMonth())>8 ? (time.getMonth()+1) : ("0"+(time.getMonth()+1));
	var date= parseInt(time.getDate())>9 ? time.getDate() : ("0"+time.getDate());
	var hour = parseInt(time.getHours())>9 ? time.getHours() : ("0"+time.getHours());
	var minute = parseInt(time.getMinutes())>9 ? time.getMinutes() : ("0"+time.getMinutes());
	var second = parseInt(time.getSeconds())>9 ? time.getSeconds() : ("0"+time.getSeconds());
	return time.getFullYear() +"-" + (month) 
			+"-"+date +" " +hour+":" 
			+ minute + ":" + second;
};

/**
 * 判断时间是否符号 yyyy-mm-dd HH:mm:ss 格式
 */
MZ.VideoUtil.isDate = function(str){
	var reg=/^(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2}):(\d{2})$/; 
    var r=str.match(reg); 
    if(r==null) return false; 
    r[2]=r[2]-1; 
    var d= new Date(r[1],r[2],r[3],r[4],r[5],r[6]); 
    if(d.getFullYear()!=r[1]) return false; 
    if(d.getMonth()!=r[2]) return false; 
    if(d.getDate()!=r[3]) return false; 
    if(d.getHours()!=r[4]) return false; 
    if(d.getMinutes()!=r[5]) return false; 
    if(d.getSeconds()!=r[6]) return false; 
    return true; 
};

/**
 * 判断字符串长度(中文占两个字节)
 */
MZ.VideoUtil.getStringLen = function(result){
	var str = $.trim(result);
	var len = 0;
	if(result != undefined){
		len = str.replace(/[^\x00-\xff]/g, '**');
	}
	return len;
};

MZ.VideoUtil.validateInputImei = function($dom){
	$dom.keyup(function( event ){
		var start = this.selectionStart,
        	end = this.selectionEnd;
		$(this).val($(this).val().replace(/[^0-9,]/g, ''));
        $(this).val($(this).val().replace(/^\,/g, ""));
        $(this).val($(this).val().replace(/\,{2,}/g, ","));
        $(this).val($(this).val().replace(/\,{2,}$/g, ","));
        this.setSelectionRange(start, end);
	}).bind("paste", function () {  //CTR+V
		$(this).val($(this).val().replace(/[^0-9,]/g, ''));
        $(this).val($(this).val().replace(/^\,/g, ""));
        $(this).val($(this).val().replace(/\,{2,}/g, ","));
        $(this).val($(this).val().replace(/\,{2,}$/g, ","));
    }).css("ime-mode", "disabled");
};

MZ.VideoUtil.validateInputVersion = function($dom){
	$dom.keyup(function (event) {
        var k = event.keyCode;
        if (k == 37 || k == 38 || k == 39 || k == 40 || k == 8 || k == 46) {
            return;
        }
        var start = this.selectionStart,
            end = this.selectionEnd;
        $(this).val($(this).val().replace(/[^0-9.]/g, ''));
        $(this).val($(this).val().replace(/^\./g, ""));
        $(this).val($(this).val().replace(/\.{2,}/g, "."));
        this.setSelectionRange(start, end);
    }).bind("paste", function ( event ) {  //CTR+V
    	 var start = this.selectionStart,
         	end = this.selectionEnd;
        $(this).val($(this).val().replace(/[^0-9.]/g, ''));
        $(this).val($(this).val().replace(/^\./g, ""));
        $(this).val($(this).val().replace(/\.{2,}/g, "."));
        this.setSelectionRange(start, end);
    }).blur(function( event ){
    	$(this).val($(this).val().replace(/\.{1,}$/g, ""));
    }).css("ime-mode", "disabled");
};

/**
 * 文本框限制只能输入小数
 */
MZ.VideoUtil.onlyPressDecimals = function(id,fixed){
	 /*JQuery 限制文本框只能输入数字和小数点*/  
   $(id).keyup(function(event){
   	   var k = event.keyCode;
       if (k == 37 || k == 38 || k == 39 || k == 40 || k == 8 || k == 46) {
           return;
       }
       var start = this.selectionStart,
           end = this.selectionEnd;
       $(this).val($(this).val().replace(/[^0-9.]/g, ''));
       $(this).val($(this).val().replace(/^\./g, ""));
       $(this).val($(this).val().replace(/\.{2,}/g, "."));
       $(this).val($(this).val().replace(".", "$#$").replace(/\./g, "").replace("$#$", "."));
       var str = ($(this).val()).substr(($(this).val()).indexOf('.'));
       if (str.length >= (fixed+2)) {
           var num = new Number($(this).val());
           $(this).val(num.toFixed(fixed));
       }
       this.setSelectionRange(start, end);
   }).bind("paste",function(){  //CTR+V事件处理      
   	var k = event.keyCode;
       if (k == 37 || k == 38 || k == 39 || k == 40 || k == 8 || k == 46) {
           return;
       }
       var start = this.selectionStart,
           end = this.selectionEnd;
       $(this).val($(this).val().replace(/[^0-9.]/g, ''));
       $(this).val($(this).val().replace(/^\./g, ""));
       $(this).val($(this).val().replace(/\.{2,}/g, "."));
       $(this).val($(this).val().replace(".", "$#$").replace(/\./g, "").replace("$#$", "."));
       var str = ($(this).val()).substr(($(this).val()).indexOf('.'));
       if (str.length >= (fixed+2)) {
           var num = new Number($(this).val());
           $(this).val(num.toFixed(fixed));
       }
       this.setSelectionRange(start, end);
   }).bind("contextmenu", function() { 
   		return false;
   }).css("ime-mode", "disabled"); //CSS设置输入法不可用 
};

MZ.VideoUtil.onlyPressNum = function($dom){
	$dom.keypress(function (event) {
		var start = this.selectionStart,
        	end = this.selectionEnd;
		$(this).val($(this).val().replace(/[^0-9]/g, ''));
	    this.setSelectionRange(start, end);
	}).keyup(function(event){
		var start = this.selectionStart,
    		end = this.selectionEnd;
		$(this).val($(this).val().replace(/[^0-9]/g, ''));
	    this.setSelectionRange(start, end);
	}).bind("paste",function(){
		var start = this.selectionStart,
		end = this.selectionEnd;
		$(this).val($(this).val().replace(/[^0-9]/g, ''));
	    this.setSelectionRange(start, end);
	}).bind("contextmenu", function() { 
   		return false;
	}).css("ime-mode", "disabled");
};

MZ.VideoUtil.validateColor = function(obj){
	var flag = true;
	var str = $.trim(obj.val());
	var reg = /[0-9a-fA-F]+/;
	if(str.length != 6 && str.length != 8){
		flag = false;
	}
	if(!reg.test(str)){
		flag = false;
	}
	return flag;
};

MZ.VideoUtil.onlyPressColor = function(obj,tipName){
	obj.on("keyup change keydown", function () {
	   	   var str=$(this).val();
	   	   var strLen=str.length;
	   	   var flag=true;
	   	   switch(strLen){
	   	   case 0:
	   		   flag=true;
	   		   break;
	   	   case 1:
	   		   var reg = /^[0-9a-fA-F]{1}/;
	   		   if(!reg.test(str)) flag=false;
	   		   break;
	   	   case 2:
	   		   var reg = /^[0-9a-fA-F]{2}/;
	   		   if(!reg.test(str)) flag=false;
	   		   break;
	   	   case 3:
	   		   var reg = /^[0-9a-fA-F]{3}/;
	   		   if(!reg.test(str)) flag=false;
	   		   break;
	   	   case 4:
	   		   var reg = /^[0-9a-fA-F]{4}/;
	   		   if(!reg.test(str)) flag=false;
	   		   break;
	   	   case 5:
	   		   var reg = /^[0-9a-fA-F]{5}/;
	   		   if(!reg.test(str)) flag=false;
	   		   break;
	   	   case 6:
	   		   var reg = /^[0-9a-fA-F]{6}/;
	   		   if(!reg.test(str)) flag=false;
	   		   break;
	   	  default:
	   		   flag=false;	   		
	   	   }
	   	   return flag;
	    });
};

/**
 * 操作按钮（禁用、使用按钮、更换按钮背景图片）
 * flag : false,表示按钮可用,反之表示禁用
 * imageUrl : 背景图片url
 * positionX/positionY : 图片起始位置
 */
MZ.VideoUtil.buttonHandler = function(btId,imageUrl,positionX,positionY,flag){
	if(btId == undefined || btId == ""){
		return;
	}
	if(flag != undefined){
		$(btId).attr("disabled",flag);
	}
	if(imageUrl != "" && imageUrl != undefined){
		$(btId).css("background-image","url("+imageUrl+")");
	}
	if(positionX!=undefined && positionY != undefined){
		$(btId).animate({"background-positionY":positionY},positionX);
	}
};

MZ.VideoUtil.GoBack = function(versionType,pageType){
	var version = MZ.VideoResources.VersionType[versionType];
	var url = "";
	if(version == "TUDOU" || version == "YOUKU" || version == "TENCENT"){
		url = pageType == MZ.VideoResources.categoryPageType[0] ?  
				"/manage/category/category-single-manage?cp="+version 
				: "/manage/channelEdit/channelEdit-manage?cp="+version;
	}else{
		url = pageType == MZ.VideoResources.categoryPageType[0] ?
				"/manage/category/category-manage?cp="+version 
				: "/manage/channelEdit/channelEdit-manage?cp="+version;
	}
	window.location.href = url;
};

MZ.VideoUtil.getVersionEnum = function(versionType){
	if(versionType == MZ.VideoResources.VersionType[0]){
		return 3;
	}else if(versionType == MZ.VideoResources.VersionType[1]){
		return 2;
	}
};

MZ.VideoUtil.loadSelectItem = function(spanId, typeData, id, withAll, type) {
	var select = $(document.createElement("select"));
	if (withAll && !type) {
		select.append("<option value='-1' selected='selected'>全部</option>");
	}
	
	var vals = [];
	
	for (data in typeData) {
		if ( vals.contains(data) || vals.contains(typeData[data]) ) {
			continue;
		}
		vals.push(data);
		vals.push(typeData[data]);
		select.append("<option value='" + data + "'"
				+ (type == data ? " selected='selected '" : "") + ">"
				+ typeData["" + data] + "</option>");
	}
	select.attr('id', id);
	select.attr('name', id);
	$("#" + spanId).append(select);
};

//按照原本数据顺序生成select
//obj:{key,value}
MZ.VideoUtil.loadSelectItemVersion2 = function(spanId, typeData, id, withAll, type) {
	var select = $(document.createElement("select"));
	if (withAll && !type) {
		select.append("<option value='-1' selected='selected'>全部</option>");
	}
	
	var vals = [];
	
	for (var i=0;i<typeData.length;i++) {
		if ( vals.contains(typeData[i].key) ) {
			continue;
		}
		vals.push(typeData[i].key);
		select.append("<option value='" + typeData[i].key + "'"
				+ (type == typeData[i].key ? " selected='selected '" : "") + ">"
				+ typeData[i].value + "</option>");
	}
	select.attr('id', id);
	select.attr('name', id);
	$("#" + spanId).append(select);
};




MZ.VideoUtil.getUrl = function(url) {
	return "http://" + window.location.host + url;
};

//channelEdit 频道编辑
MZ.VideoUtil.toChannelEdit = function(type,versionType, parentId, id, topChannelId) {
	var parentName = "";
	var parentType = "";
	//顶级栏目id
	var channelId = 0;
	var pageType = $("#pageType").val();
	// 新增取父ID，修改取当前的ID,状态改变，发布会把这些有修改的重新刷新缓存
	$.getJSONSjax('/manage/channelEdit/edit/changeStatus?id='+(parentId==0?id:parentId),function(data){
		if( data != 'SUCCESS' ){
			jAlert('服务器繁忙，请稍后再试！','提示');
			return;
		}
	});
	$.getJSONSjax(
					MZ.VideoUtil.getUrl("/manage/channelEdit/detail/" + parentId),
					function(data) {
						if (data != null) {
							parentName = data.title;
							parentType = data.type;
							channelId = data.channelId;
						}
						switch (type) {
							case 'top': {
								if(channelId == MZ.VideoResources.mzChannel['会员']){
									if( id == 0 ){
										window.location.href = "/manage/channelEdit/edit/"
											+ parentId + "/" + id + "?parentName="
											+ encodeURIComponent(parentName) + "&type=videoes"
											+ "&pType=" + parentType
											+"&versionType="+versionType+"&pageType="+pageType;
									}else{
										window.location.href = "/manage/channelEdit/edit/"
											+ parentId + "/" + id + "?parentName="
											+ encodeURIComponent(parentName) + "&type="
											+ type + "&pType=" + parentType
											+"&versionType="+versionType+"&pageType="+pageType;
									}
								}else{
									window.location.href = "/manage/channelEdit/edit/"
										+ parentId + "/" + id + "?parentName="
										+ encodeURIComponent(parentName) + "&type="
										+ type + "&pType=" + parentType
										+"&versionType="+versionType+"&pageType="+pageType;
								}
								break;
							}
							case 'banner': {
								window.location.href = "/manage/banner/edit/"
										+ parentId + "/" + id + "?parentName="
										+ encodeURIComponent(parentName)+ "&type="
										+ type + "&pType=" + parentType
										+"&versionType="+versionType+"&pageType="+pageType;
								break;
							}
							case 'subject': {
								window.location.href = "/manage/channelEdit/categorySubject/edit/"
										+ parentId
										+ "/"
										+ id
										+ "?parentName="
										+ parentName + "&type=" + type + "&pType=" + parentType
										+"&versionType="+versionType+"&pageType="+pageType;
								break;
							}
							case 'videoes': {
								window.location.href = "/manage/channelEdit/videoes/edit/"
										+ parentId
										+ "/"
										+ id
										+ "?parentName="
										+ encodeURIComponent(parentName)
										+ "&type="
										+ type + "&pType=" + parentType
										+"&versionType="+versionType
										+"&topChannelId="+topChannelId+"&pageType="+pageType;
								break;
							}
							case 'entrance': {
								window.location.href = "/manage/channelEdit/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName) + "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
								break;
							}
							case 'parent': {
								if ( id == 0 ) {
									window.location.href = "/manage/channelEdit/videoes/edit/"
										+ parentId + "/" + id + "?parentName="
										+ encodeURIComponent(parentName) + "&type=videoes"
										+ "&pType=" + parentType
										+"&versionType="+versionType
										+"&topChannelId="+topChannelId+"&pageType="+pageType;
								} else {
									window.location.href = "/manage/channelEdit/edit/"
										+ parentId + "/" + id + "?parentName="
										+ encodeURIComponent(parentName) + "&type="
										+ type + "&pType=" + parentType
										+"&versionType="+versionType
										+"&topChannelId="+topChannelId+"&pageType="+pageType;
								}
								
								break;
							}
							case 'vip': {
								if( id == 0 ){
									window.location.href = "/manage/channelEdit/videoes/edit/"
										+ parentId + "/" + id + "?parentName="
										+ encodeURIComponent(parentName) + "&type=videoes"
										+ "&pType=" + parentType
										+"&versionType="+versionType
										+"&topChannelId="+topChannelId+"&pageType="+pageType;
								}else{
									window.location.href = "/manage/channelEdit/edit/"
										+ parentId + "/" + id + "?parentName="
										+ encodeURIComponent(parentName) + "&type="
										+ type + "&pType=" + parentType
										+"&versionType="+versionType
										+"&topChannelId="+topChannelId+"&pageType="+pageType;
								}
								break;
							}
							case 'dailyUpdate': {
								window.location.href = "/manage/channelEdit/dailyUpdate/edit/"
										+ parentId
										+ "/"
										+ id
										+ "?parentName="
										+ encodeURIComponent(parentName)
										+ "&type="
										+ type + "&pType=" + parentType
										+"&versionType="+versionType+"&pageType="+pageType;
								break;
							}
							case 'hot': {
								
									window.location.href = "/manage/channelEdit/hot/edit/"
										+ parentId
										+ "/"
										+ id
										+ "?parentName="
										+ encodeURIComponent(parentName)
										+ "&type="
										+ type + "&pType=" + parentType
										+"&versionType="+versionType+"&pageType="+pageType;
									break;
								
								
							}
							case 'singleHot':{
								window.location.href = "/manage/channelEdit/hot/edit/"
									+ parentId
									+ "/"
									+ id
									+ "?parentName="
									+ encodeURIComponent(parentName)
									+ "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
								break;
							}
							case 'rank': {		
								window.location.href = "/manage/channelEdit/videoes/edit/"
									+ parentId
									+ "/"
									+ id
									+ "?parentName="
									+ encodeURIComponent(parentName)
									+ "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType
									+"&topChannelId="+topChannelId+"&pageType="+pageType;
							break;
							}
							case 'channel': {
								window.location.href = "/manage/channelEdit/videoes/edit/"
										+ parentId + "/" + id + "?parentName="
										+ encodeURIComponent(parentName) + "&type="
										+ type + "&pType=" + parentType
										+"&versionType="+versionType
										+"&topChannelId="+topChannelId+"&pageType="+pageType;
								break;
							}
							case 'movie': {
								window.location.href = "/manage/channelEdit/onlineMovie/edit/"
										+ parentId + "/" + id + "?parentName="
										+ encodeURIComponent(parentName) + "&type="
										+ type + "&pType=" + parentType
										+"&versionType="+versionType+"&pageType="+pageType;
								break;
							}
							case 'channelEntrance':{
								window.location.href = "/manage/channelEdit/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName) + "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
								break;
							}
							case 'userChannel':{
								window.location.href = "/manage/channelEdit/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName) + "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
								break;
							}
							case 'guessYouLike':{
								window.location.href = "/manage/channelEdit/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName) + "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
								break;
							}
							case 'broadcast' : {
								window.location.href = "/manage/broadcast/edit/"
									+ id + "?parentName="
									+ encodeURIComponent(parentName) + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType+"&topChannelId=" + parentId;
								break;
							}
							case 'topNotice' : {
								window.location.href = MZ.VideoUtil.getUrl("/manage/topNotice/edit/"+ id)
								+ "?parentName="
								+ encodeURIComponent(parentName) + "&pType=" + parentType
								+"&versionType="+versionType+"&pageType="+pageType+"&topChannelId=" + parentId;
								break;
							}
							case 'hotEntrance' : {
								window.location.href = "/manage/broadcast/edit/hotEntrance/"
									+ id + "?parentName="
									+ encodeURIComponent(parentName) + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType+"&topChannelId=" + parentId;
								break;
							}
						}
					});

};

MZ.VideoUtil.toCategoryEdit = function(type,versionType, parentId, id) {
	var parentName = "";
	var parentType = "";
	var pageType = $("#pageType").val();
	// 新增取父ID，修改取当前的ID,状态改变，发布会把这些有修改的重新刷新缓存
	$.getJSONSjax('/manage/category/edit/changeStatus?id='+(parentId==0?id:parentId),function(data){
		if( data != 'SUCCESS' ){
			jAlert('服务器繁忙，请稍后再试！','提示');
			return;
		}
	});
	$.getJSONSjax(
					MZ.VideoUtil.getUrl("/manage/category/detail/" + parentId),
					function(data) {
						if (data != null) {
							parentName = data.title;
							parentType = data.type;
						}
						switch (type) {
						case 'top': {
							window.location.href = "/manage/category/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName) + "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							break;
						}
						case 'banner': {
							window.location.href = "/manage/banner/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName)+ "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							break;
						}
						case 'subject': {
							window.location.href = "/manage/category/categorySubject/edit/"
									+ parentId
									+ "/"
									+ id
									+ "?parentName="
									+ parentName + "&type=" + type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							break;
						}
						case 'videoes': {
							window.location.href = "/manage/category/videoes/edit/"
									+ parentId
									+ "/"
									+ id
									+ "?parentName="
									+ encodeURIComponent(parentName)
									+ "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							break;
						}
						case 'entrance': {
							if ( (MZ.VideoResources.topCategorys[parentId] 
								 || MZ.VideoResources.topCategorys[data.parentId]) && id == 0 ) {
								/* 
								 * 入口位下暂不支持添加入口位，目前新增子栏目默认首选项是热点，故点击添加子栏目时默认跳转到hot编辑页面
								 * since 2015/01/06
								 */
								window.location.href = "/manage/category/hot/edit/"
									+ parentId
									+ "/"
									+ id
									+ "?parentName="
									+ encodeURIComponent(parentName)
									+ "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
								
							} else if ((MZ.VideoResources.topCategorys[parentId] 
										|| MZ.VideoResources.topCategorys[data.parentId] ) 
										&& id != 0) {
								window.location.href = "/manage/category/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName) + "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							} else {
								window.location.href = "/manage/category/videoes/edit/" + parentId
									+ "/"+id+"?parentName=" + encodeURIComponent(parentName) 
									+ "&type=" + type + "&pType="+parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							}
							
							break;
						}
						case 'parent': {
							if ( id == 0 ) {
								window.location.href = "/manage/category/videoes/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName) + "&type=videoes"
									+ "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							} else {
								window.location.href = "/manage/category/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName) + "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							}
							
							break;
						}
						case 'vip': {
							if( id == 0 ){
								window.location.href = "/manage/category/videoes/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName) + "&type=videoes"
									+ "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							}else{
								window.location.href = "/manage/category/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName) + "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							}
							break;
						}
						case 'dailyUpdate': {
							window.location.href = "/manage/category/dailyUpdate/edit/"
									+ parentId
									+ "/"
									+ id
									+ "?parentName="
									+ encodeURIComponent(parentName)
									+ "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							break;
						}
						case 'hot': {
							
								window.location.href = "/manage/category/hot/edit/"
									+ parentId
									+ "/"
									+ id
									+ "?parentName="
									+ encodeURIComponent(parentName)
									+ "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
								break;
							
							
						}
						case 'singleHot':{
							window.location.href = "/manage/category/hot/edit/"
								+ parentId
								+ "/"
								+ id
								+ "?parentName="
								+ encodeURIComponent(parentName)
								+ "&type="
								+ type + "&pType=" + parentType
								+"&versionType="+versionType+"&pageType="+pageType;
							break;
						}
						case 'rank': {		
							window.location.href = "/manage/category/videoes/edit/"
								+ parentId
								+ "/"
								+ id
								+ "?parentName="
								+ encodeURIComponent(parentName)
								+ "&type="
								+ type + "&pType=" + parentType
								+"&versionType="+versionType+"&pageType="+pageType;
						break;
						}
						case 'channel': {
							window.location.href = "/manage/category/videoes/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName) + "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							break;
						}
						case 'movie': {
							window.location.href = "/manage/category/onlineMovie/edit/"
									+ parentId + "/" + id + "?parentName="
									+ encodeURIComponent(parentName) + "&type="
									+ type + "&pType=" + parentType
									+"&versionType="+versionType+"&pageType="+pageType;
							break;
						}
						case 'channelEntrance':{
							window.location.href = "/manage/category/edit/"
								+ parentId + "/" + id + "?parentName="
								+ encodeURIComponent(parentName) + "&type="
								+ type + "&pType=" + parentType
								+"&versionType="+versionType+"&pageType="+pageType;
							break;
						}
						case 'userChannel':{
							window.location.href = "/manage/category/edit/"
								+ parentId + "/" + id + "?parentName="
								+ encodeURIComponent(parentName) + "&type="
								+ type + "&pType=" + parentType
								+"&versionType="+versionType+"&pageType="+pageType;
							break;
						}
						case 'guessYouLike':{
							window.location.href = "/manage/category/edit/"
								+ parentId + "/" + id + "?parentName="
								+ encodeURIComponent(parentName) + "&type="
								+ type + "&pType=" + parentType
								+"&versionType="+versionType+"&pageType="+pageType;
							break;
						}
						case 'broadcast' : {
							window.location.href = "/manage/broadcast/edit/"
								+ id + "?parentName="
								+ encodeURIComponent(parentName) + "&pType=" + parentType
								+"&versionType="+versionType+"&pageType="+pageType+"&topChannelId=" + parentId;
							break;
						}
						case 'topNotice' : {
							window.location.href = MZ.VideoUtil.getUrl("/manage/topNotice/edit/"+ id)
							+ "?parentName="
							+ encodeURIComponent(parentName) + "&pType=" + parentType
							+"&versionType="+versionType+"&pageType="+pageType+"&topChannelId=" + parentId;
							break;
						}
						case 'discovery' : {
							window.location.href = "/manage/category/discovery/edit/"
								+ parentId + "/" + id + "?parentName="
								+ encodeURIComponent(parentName) + "&type="
								+ type + "&pType=" + parentType
								+"&versionType="+versionType+"&pageType="+pageType;
						}
						case 'guideLink' : {
							window.location.href = "/manage/category/guideLink/edit/"
								+ parentId + "/" + id + "?parentName="
								+ encodeURIComponent(parentName) + "&type="
								+ type + "&pType=" + parentType
								+"&versionType="+versionType+"&pageType="+pageType;
						}
						}
					});

};

//频道编辑版本
MZ.VideoUtil.categorySelectChanged = function() {
	var type = $("#categoryType").getSelectedValue();
	var tmp_parentId = $("#hide_id").val();
	var tmp_hide_parentName = encodeURIComponent($("#hide_parentName").val());
	var parent_type = $("#parent_type").val();
	var versionType = $("#versionType").val();
	var pageType = $("#pageType").val();
	var baseUrl = "/manage/category";
	if(pageType == MZ.VideoResources.categoryPageType[1]){
		baseUrl = "/manage/channelEdit";
	}
	switch (type) {
		case "banner": {
			window.location.href = "/manage/banner/edit/" + tmp_parentId
					+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
					+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case "entrance": {
			window.location.href = baseUrl+"/edit/" + tmp_parentId
					+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
					+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case 'videoes': {
			window.location.href = baseUrl+"/videoes/edit/" + tmp_parentId
					+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
					+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
	
		}
		case "parent": {
			window.location.href = baseUrl+"/edit/" + tmp_parentId
					+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
					+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case "subject": {
			window.location.href = baseUrl+"/categorySubject/edit/"
					+ tmp_parentId + "/0?parentName=" + tmp_hide_parentName
					+ "&type=" + type+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case 'dailyUpdate': {
			window.location.href = baseUrl+"/dailyUpdate/edit/"
					+ tmp_parentId + "/0?parentName=" + tmp_hide_parentName
					+ "&type=" + type+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case 'rank': {
			window.location.href = baseUrl+"/videoes/edit/" + tmp_parentId
				+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
				+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
				break;
		}
		case 'channel': {
			window.location.href = baseUrl+"/videoes/edit/" + tmp_parentId
					+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
					+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case 'hot': {
			window.location.href = baseUrl+"/hot/edit/" + tmp_parentId
			+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
			+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case 'singleHot': {
			window.location.href = baseUrl+"/hot/edit/" + tmp_parentId
			+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
			+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case 'movie':{
			window.location.href = baseUrl+"/onlineMovie/edit/"+tmp_parentId
					+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
					+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case 'channelEntrance':{
			window.location.href = baseUrl+"/edit/" + tmp_parentId
			+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
			+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case 'userChannel':{
			window.location.href = baseUrl+"/edit/" + tmp_parentId
			+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
			+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case 'guessYouLike':{
			window.location.href = baseUrl+"/edit/" + tmp_parentId
			+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
			+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case 'broadcast':{
			var pageType = $("#pageType").val();
			window.location.href = MZ.VideoUtil
					.getUrl("/manage/broadcast/add/" + $("#id").val())
					+ "?versionType="
					+ versionType
					+ "&parentType="
					+ parent_type
					+ "&pageType="
					+ pageType
					+ "&topChannelId="
					+ $("#hide_id").val()
					+ "&parentName="
					+ encodeURIComponent($("#hide_parentName").val());
	        break;
		}
		case 'topNotice':{
			var pageType = $("#pageType").val();
			window.location.href = MZ.VideoUtil.getUrl("/manage/topNotice/add")
					+ "?versionType="
					+ versionType
					+ "&parentType="
					+ parent_type
					+ "&pageType="
					+ pageType
					+ "&topChannelId="
					+ $("#hide_id").val()
					+ "&parentName="
					+ encodeURIComponent($("#hide_parentName").val());
	        break;
		}
		case 'discovery': {
			window.location.href = baseUrl+"/discovery/edit/" + tmp_parentId
					+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
					+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		case 'guideLink': {
			window.location.href = baseUrl+"/guideLink/edit/" + tmp_parentId
					+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
					+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
		default: {
			window.location.href = baseUrl+"/edit/" + tmp_parentId
					+ "/0?parentName=" + tmp_hide_parentName + "&type=" + type
					+ "&pType="+parent_type+"&versionType="+versionType+"&pageType="+$("#pageType").val();
			break;
		}
	}
};


MZ.VideoUtil.onecpChannelChanged=function(){
	var type = $("#onecpChannel").getSelectedValue();
	if(type=="INTERFACEDATA"){
		$("#onecpaddChannel").remove();
		MZ.VideoUtil.loadSelectItem('onecpaddChannelSpan',
				MZ.VideoResources.interfaceData, 'onecpaddChannel', false,1);
	}else{
		$("#onecpaddChannel").remove();
		MZ.VideoUtil.loadSelectItem('onecpaddChannelSpan',
				MZ.VideoResources.actionData, 'onecpaddChannel', false,1);
	}
	
};

MZ.VideoUtil.initSampleCpSelectItem=function(){
	$.getJSONSjax("/manage/channel/hotInterfaceDataList/", function(data){
		if(data && data.length>0){
			MZ.VideoUtil.loadSelectItem('onecpaddChannelSpan',
					data, 'onecpaddChannel', false,1);
		}
	});
};

MZ.VideoUtil.initCategoryType = function(){
	var typeData = {};
	var type = $("#parent_type").val();
	var parId = $("#hide_id").val();
	var id = $("#id").val();
	$.getJSONSjax("/manage/category/detail/" + parId, function(data){
		var parentId = data.parentId;
		var version = data.version;
		var pageType = data.pageType;
		var channelId = data.channelId;
		var cpVersion = MZ.VideoResources.VersionType[version];
		if ( type == "top" ) {
			typeData = {
				"parent" : "父栏目",
				"entrance" : "入口位",
				"banner" : "宣传图",
				"guessYouLike" : "猜你喜欢",
				"vip" : "会员栏目",
				"broadcast" : "广播位",
				"topNotice" : "顶部通知位",
			};
			
			if (pageType == 'homePage') {
				delete typeData.topNotice;
			}
			if (version == MZ.VideoResources.VersionType["MULTI"]){
				delete typeData.vip;
			}
			if (pageType == MZ.VideoResources.categoryPageType[1]){
				delete typeData.guessYouLike;
				//频道编辑 --> 顶级栏目编辑
				if(version != MZ.VideoResources.VersionType["MULTI"] && id > 0){
					typeData.top = "顶级栏目";
				}
				if(channelId == MZ.VideoResources.mzChannel['会员']){
					delete typeData.parent;
					delete typeData.parent;
				}
			}
		} else if ( type == "parent"  || type == "vip") {
			typeData = {
				"videoes" : "视频合集",
				// 暂时屏敝掉[最近更新]，该块用于导流位
				// "dailyUpdate" : "最近更新",
				"guideLink" : "关键字导流位",
				"banner" : "宣传图"
			};
			if(type == "vip"){
				delete typeData.dailyUpdate;
			}
			if(pageType == MZ.VideoResources.categoryPageType[1]){
				delete typeData.dailyUpdate;
			}
		} else if ( type == "entrance" ) { 
			/**
			 * 暂时屏蔽入口entrance/banner/parent
			 * since 2014/12/31
			 */
			if(cpVersion == "TENCENT"){
				typeData = {
					"movie" : "院线影片",
					"channelEntrance" : "频道入口",
					"userChannel" : "自频道广场",
					"channel" : "频道",
					"discovery" : "发现入口"
				};
			} else if (cpVersion == "YOUKU"){
				typeData = {
					"hot" : "热点",
					"subject" : "专题",
					"rank" : "排行榜",
					"movie" : "院线影片",
					"channelEntrance" : "频道入口",
					"userChannel" : "自频道广场",
					"channel" : "频道",
					"discovery" : "发现入口"
				};
			}
			
			if(version == 3){
				delete typeData.userChannel;
			}
			
			if ( parId == 1 || parentId == 1) {
				delete typeData.channel;
			}
			//频道编辑下入口位只能添加频道和宣传图
			if ( parId == 2 || parentId == 2 || parId == 1001 || 
					parentId == 1001 || parId == 4001 || parentId == 4001) {
				typeData = {
					"channel" : "频道",
					"banner" : "宣传图"
				};
			}
		}
		
		MZ.VideoUtil.loadSelectItem('categoryTypeSpan', typeData, 'categoryType', false, $("#hide_type").val());
		if ( $("#id").val() != "0" ) {
			$("#categoryType").attr("disabled", "disabled");
		}
	});
};

MZ.VideoUtil.loadLabelOptions = function(parent, parentLevel, inline, prevChannelId) {
	var parentId = "";
	var level = "";	
	var isChannel = false;
	if (parent.target) {
		var data = parent.data;
		parent = data.ele;
		$(parent).nextAll().remove();
		
		if ( !$(parent).getSelectedValue() && prevChannelId == undefined) {  //未选择父标签，不再取下级标签
			return;
		}
		
		inline = data.inline;
		level = parseInt(data.level) + 1;
	}
	if ($(parent).get(0).tagName == 'SELECT') {
		parentId = $(parent).getSelectedValue();
		if ( parentId.indexOf("channel") != -1 ) {//id="channel123"
			parentId = parentId.substring(7);
			isChannel = true;
		}
	}
	if(prevChannelId){
		if(prevChannelId.indexOf("channel") != -1){
			isChannel = true;
			parentId = prevChannelId.substring(7);
		}else{
			parentId = prevChannelId;
		}
	}
	var paramObj = {
		parentId : parentId,
		level: parentLevel || level || 1
	};
	if ( level == 2 && parentId == 1 ) {  //取魅族频道（二级标签）
		paramObj.labelType = 1;
	}
	
	if ( isChannel ) {  //取魅族频道下标签
		paramObj.channelId = parentId;
		paramObj.parentId = "0";
	}
	var params = {
		"param" : $.toJSON(paramObj)
	};
	
	$.postJSON(MZ.VideoUtil.getUrl("/manage/label/search"), params, function(
			data) {
		if (!data || data.totalCount == 0) {
			return;
		} else {
			data = data.list;
			var next = $("<div></div>");
			var what = $("<select></select>");
			var level = !isNaN(parseInt(parentLevel)) ? (parseInt(parentLevel) + 1) : (parseInt($(parent)
					.attr("id").split("_")[1]) + 1);
			what.attr('id', "labelSelect_" + level);
			what.bind('change', {ele: what.get(0), level: level, inline: inline}, MZ.VideoUtil.loadLabelOptions);
			var str = "<option value=\"\">请选择</option>";
			for ( var i = 0; i < data.length; i++) {
				var lab = data[i];
				if(lab.status == 0){
					continue;
				}
				str += "<option value='" + lab.id + "'>" + lab.title
						+ "</option>";
			}
			what.append(str);
			inline ? (next = what) : next.append(what);
			if ($(parent).get(0).tagName == 'SELECT') {
				$(parent).after(next);
			} else {
				$(parent).append(next);
			}
			var selectWidth = what.width();
			what.css("width",selectWidth+10);
		}
	});
};

MZ.VideoUtil.loadMZChannelList = function(withAll,bindId, callable, channelId) {
	var version = $("#versionType").val();
	var url = "/manage/channel/list";
	if(version){
		url = '/manage/channel/listByVersion?version='+version;
	}
	$.getJSONSjax(MZ.VideoUtil.getUrl(url), function(data) {
		if (!data.error) {
			var $select = $('<select name="selectChannel" id="selectChannel"></select>');
			if( withAll ){
				$select.append($("<option selected='selected' value='-1'>全部</option>"));
			}
			for ( var i = 0; i < data.length; i++) {
				var channel = data[i];
				var temp = $("<option>" + channel.name + "</option>");
				temp.attr('value', channel.id);
				if (channelId == channel.id) {
					temp.attr('selected', 'selected');
				}
				$select.append(temp);
			}
			$('#' + bindId).append($select);
			if (callable) {
				callable();
			}
			if (channelId && channelId != 0) {// 修改的时候不能已经选择的频道
				$select.attr('disabled', 'disabled');
			} else {
				if (callable) {
					$("#selectChannel").bind('change', callable);
				}
			}
			if($("#categoryType").length>0  ){
				if($("#categoryType").getSelectedValue() != "vip"){
					$("#selectChannel option[value=98]").remove();
				}
				if($("#categoryType").getSelectedValue() == 'hot'
					|| $("#categoryType").getSelectedValue() == 'parent'){
					//删除热点、其他、自频道 
					$("#selectChannel option[value=17]").remove();
					$("#selectChannel option[value=21]").remove();
					$("#selectChannel option[value=99]").remove();
				}
			}
		}
	});
};

//{
//	parId:父栏目id,parType:父栏目类型,
//	id:栏目id,type:栏目类型,
//	fn:验证通过后回调函数
//}
MZ.VideoUtil.validCategory = function(opts){
	var typeValid = false;//类型验证
	var numValid = false;//数量验证
	var numFlag = true;
	var entceFlag =true;
	var parType = opts.parType;
	var type = opts.type;
	var version = opts.version;
	if ( parType == "entrance" && type != "banner" ) {//入口位下只能存在一种类目类型（宣传图除外）
		typeValid = true;
	}
	if ( parType == "parent" || type == "guessYouLike" 
		|| ((parType == "top" || parType == "vip") && type == "videoes" )) {//父栏目下每种栏目类型只能有一个
		numValid = true;
	}
	
	// 关键字导流位
	if ( type == "guideLink" ) {
		numValid = false;
	}
	
	if(parType == "entrance" && type != "videoes" && 
			type != "hot" && type != "singleHot" && 
			type != "banner" && type !="rank"){
		numValid = true;
	}
	if ( opts.id && opts.id > 0 ) {//修改不验证
		typeValid = false;
		numValid = false;
	}
	if ( !typeValid && !numValid ) {
		opts.fn && opts.fn.call(this);
		return;
	}
	var types = MZ.VideoResources.CategoryType;
	var url = "/manage/category/list/getCategoryByParentAndType";
	var param = {parentId: opts.parId, type: type};
	numValid && $.postJSON(url, param, function(data){
		if ( data && data.result > 0 ) {
			var msg = "一个 [" + types[parType] + "] 下只能有一个 [" + types[type] + "] ";
			jAlert(msg, "提示");
			entceFlag = false;
			numFlag = false;
			return;
		}
		if(!(parType == "entrance" && type != "videoes" 
			&& type != "singleHot" && type != "hot"  && type != "banner")){
			opts.fn && opts.fn.call(this);
		}
	});
	setTimeout(function(){
		if(!numFlag){
			return;
		}
		var url = "/manage/category/list/child/" + opts.parId+"?version="+version;
		typeValid && $.postJSON(url, {}, function(data){
			var hasType = "";
			for ( var i = 0, len = data.list.length; i < len; i++ ) {
				var categoryType = data.list[i].type;
				if ( categoryType == "banner" ) { continue; }
				hasType = categoryType;
				break;
			}
			var pattern = "hot";
			//非热点栏目添加子栏目
			if(hasType && hasType.toLowerCase().indexOf(pattern)<0){
				if (hasType != type ) {
					entceFlag = false;
					jAlert("一个 [" + types[parType] + "] 下只允许一种栏目类型", "提示");
					return;
				}
			}
			//热点栏目添加子栏目
			if(hasType && hasType.toLowerCase().indexOf(pattern) >= 0){
				if(type.toLowerCase().indexOf(pattern)<0){
					entceFlag = false;
					jAlert("一个 [" + types[parType] + "] 下只允许一种栏目类型", "提示");
					return;
				}
			}
			if(!(parType == "entrance" && type != "videoes" 
				&& type != "singleHot" && type != "hot" 
				&& type != "banner" && type != "subject")){
				opts.fn && opts.fn.call(this);
			}else if(parType == "entrance" && type != "videoes" 
				&& type != "singleHot" && type != "hot"  
				&& type != "banner" && type != "subject" && entceFlag){
				opts.fn && opts.fn.call(this);
			}
		});
	},500);
};

//页面显示视频列表时候使用
//初始小图片为固定图片，点击时弹框显示大图片。
MZ.VideoUtil.initImgDialog = function(containId){
	containId = containId || "mainList";
	$("body").append("<div id='showImgDialog' style='display: none'>" +
			"<img id='showImg' src='' alt='视频图片' width='400px;' height='255px;'/></div>");
	$('#showImgDialog').dialog({  
        autoOpen:false, 
        resizable:false,
        height:380,
        width:450,  
        modal:true, 
        title:'视频图片',  
        overlay: { opacity: 0.5, background: "black" },  
        buttons:{
	        '关闭':function(){
	        	$(this).dialog("close");
	        	$("#showImg").attr("src", "");
	        }
        }
    });
	
	$("#" + containId).on("click", "img[src='/resources/video/image/video.jpg']", function(){
		var obj = eval("("+$(this).attr("imgUrl")+")");
		var videoId = obj.entityRelId || obj.id || obj.entityId;
		var categoryId = obj.categoryId==undefined?0:obj.categoryId;
		var type = obj.type==undefined?"VIDEO":obj.type;
		var imageType = obj.imageType;
		var subCategory = obj.subCategory;
		var url =  "/manage/video/reviewImages/" + videoId+"/"+categoryId+"/"+type;
		var params={
			imageType : imageType,
			subCategory : subCategory
		};
		$.postJSON(url, params, function(data){
			if(data == null || data.images == ""){
				$("#showImg").attr("src", obj.images || obj.entityRelImg);
			}else {
				$("#showImg").attr("src", data.images);
			}
			$("#showImgDialog").dialog("open");
		});
	});
};

//不破坏以前的业务新建图片显示方法
MZ.VideoUtil.initImgDialogOpVersion = function(containId){
	containId = containId || "mainList";
	$("body").append("<div id='showImgDialog' style='display: none'>" +
			"<img id='showImg' src='' alt='视频图片' width='400px;' height='255px;'/></div>");
	$('#showImgDialog').dialog({  
      autoOpen:false, 
      resizable:false,
      height:380,
      width:450,  
      modal:true, 
      title:'视频图片',  
      overlay: { opacity: 0.5, background: "black" },  
      buttons:{
	        '关闭':function(){
	        	$(this).dialog("close");
	        	$("#showImg").attr("src", "");
	        }
      }
  });
	$("#" + containId).on("click", "img[src='/resources/video/image/video.jpg']", function(){
		var obj = eval("("+$(this).attr("imgUrl")+")");
		var videoId = obj.entityRelId || obj.id || obj.entityId;
		var categoryId = obj.categoryId==undefined?0:obj.categoryId;
		var type = obj.type==undefined?"VIDEO":obj.type;
		var imageType = obj.imageType;
		var subCategory = obj.subCategory;
		var url =  "/manage/video/reviewImages/" + videoId+"/"+categoryId+"/"+type;
		var params={
			imageType : imageType,
			subCategory : subCategory
		};
		$("#showImg").attr("src", obj.images || obj.entityRelImg);
		$("#showImgDialog").dialog("open");
	});
};



//图片编辑弹框
MZ.VideoUtil.initEditImgDialog = function(fn){
	$("body").append("<div style=\"display: none;\"  id=\"editImgDialog\">"
			+ "<input type=\"hidden\" id=\"editVideoId\" name=\"editVideoId\" value=\"\"/>"
			+ "<input type=\"hidden\" id=\"entityRowId\" name=\"entityRowId\" value=\"\"/>"
			+ "<input type=\"hidden\" id=\"editOriginImg\" name=\"editOriginImg\" value=\"\"/>"
			+ "<input type=\"hidden\" id=\"videoType\" name=\"videoType\" value=\"\"/>"
			+ "<input type=\"hidden\" id=\"categoryId\" name=\"categoryId\" value=\"\"/>"
			+ "<input type=\"hidden\" id=\"addType\" name=\"addType\" value=\"\"/>"
			+ "<div style=\"width: 385px;height: 160px;\">"
			+ "<img style=\"width: 385px;height: 160px;\" id=\"editImg\" src=\"\"/></div>"
		
			+ "<input type=\"text\" id=\"editImgUrl\" value=\"\" style=\"width: 385px;\"/>"
			+ "<input id=\"editImgUpload\" type=\"button\" class=\"Mbutton3\"  value=\"浏览\"/>"
			+ "<input id=\"resetImg\" type=\"button\" class=\"Mbutton3\" value=\"恢复原图\"/>"
			+ "<div><span>建议尺寸900*500以内，限JPG或PNG,500Kb以内</span></div></div>");
	
	$('#editImgDialog').dialog({  
        autoOpen:false, 
        resizable:false,
        height:380,
        width:450,  
        modal:true, 
        title:'编辑图片',  
        overlay: { opacity: 0.5, background: "black" },  
        buttons:{
        	'确认':function(){
        		var param = {
        			id: $("#editVideoId").val(),
        			images: $("#editImgUrl").val(),
        			type: $("#videoType").val(),
        			categoryId:$("#categoryId").val(),
        			addType: $("#addType").val()
        		};
        		$.postJSON(MZ.VideoUtil.getUrl("/manage/video/updImages"), param, function(data){
        			$("#editImgDialog").dialog("close");
        			if ( fn ) {
        				fn.call(this, data.result, $("#entityRowId").val(),
        						$("#editVideoId").val(), $("#videoType").val());
        			}
        		});
        	},
	        '返回':function(){$(this).dialog("close");}
        }
    });
	
	$("#resetImg").click(function(){
		if ( !$("#editOriginImg").val() ) {
			ZZtips.attachTip('resetImg','该视频无原图信息！');
		} else {
			if($("#editOriginImg").val() == $("#editImg").attr("src")){
				ZZtips.attachTip('resetImg','当前已为原图，无需恢复！');
			}else{
				$("#editImg").attr("src", $("#editOriginImg").val());
				$("#editImgUrl").val($("#editOriginImg").val());
			}
		}
	});
	
	$("#editImgUpload").uploadify({
        swf: "/resources/video/plugin/uploadify.swf", //flash文件的相对路径
        uploader: '/manage/upload/categoryImage', //后台处理程序的相对路径
        width: '80',
        height: '30',
        buttonClass: 'Mbutton3',
        fileObjName: '应用', //设置上传文件名称,默认为Filedata
        queueID: 'upload-progress', //文件队列的ID，该ID与存放文件队列的div的ID一致
        fileTypeDesc: 'png文件,jpg文件,gif文件', //用来设置选择文件对话框中的提示文本
        fileTypeExts: '*.png;*.jpg;*.gif;', //设置可以选择的文件的类型
        auto: true, //设置为true当选择文件后就直接上传了，为false需要点击上传按钮才上传
        multi: false, //设置为true时可以上传多个文件
        queueSizeLimit: 1,
        buttonText: '浏览', //浏览按钮的文本，默认值：BROWSE
        progressData: 'percentage', //上传队列显示的数据类型，percentage是百分比，speed是上传速度
        //回调函数
        onUploadError: function (errorObj) {
            if (errorObj.type === "File Size") {
                jAlert("上传的图标文件最大为500kb", "提示");
                $(this).uploadifyClearQueue();
            }
        },
        onSelectError: function (file, errorCode, errorMsg) {
        	if (file.type && ![ ".png", ".jpg", ".gif" ].contains(file.type)) {
				jAlert("不支持 " + file.type + " 格式图片上传", "提示");
				return false;
			} else if (errorCode == -120) {
				jAlert("文件大小不能为0！", "提示");
				return false;
			}
        },
        onUploadSuccess: function (file, data) {
            var json = jQuery.parseJSON(data);
            if (json.error) {
				jAlert(json.error, "提示");
				return;
			}
            if (json[0].status == 200) {
                $("#editImgUrl").val(json[0].savedUrl);
                $("#editImg").attr('src',json[0].savedUrl);
            } else {
                jAlert("上传失败，请重试", "提示");
            }
        }
    });
};

/**
 * 编辑视频图片
 * @param addType 视频添加方式（LABEL:通过标签添加/VIDEO：通过ID添加 ）
 * @param type 实体类型（ALBUM/VIDEO） 
 */
MZ.VideoUtil.editVideoImg = function(id, videoId, type,categoryId,addType,images,imagesType,subCategory){
	if ( !id || !videoId ) {return;}
	type = type || "VIDEO";
	if(categoryId == undefined || categoryId == "undefined"){
		categoryId = 0;
	}
	if(type == "undefined" || type == undefined){
		type = "VIDEO";
	}
	var defaultImg = "/resources/video/image/video-default.png";
	var url = type == "VIDEO" ? "/manage/video/editImgDetail/" + videoId+"/"+categoryId+"/"+type
				: "/manage/videoAlbum/editImgDetail/" + videoId+"/"+categoryId+"/"+type;
	var param = {"subCategory":subCategory,"imageType":imagesType};
	if(type == "CALENDAR"){
		url = "/manage/calendarHomePageCard/editImage";
		param = {"id" : id , "entityId" : videoId};
	}
	$.postJSON(url, param, function(data){
		$("#editImg").attr("src", data && images || data.images || defaultImg);
		$("#editImgUrl").val(data && images || data.images ||  "");
		$("#editImgUrl").attr("disabled","true");
		$("#editOriginImg").val(data && data.originImage || "");
		$("#videoType").val(type);
		$("#categoryId").val(categoryId);
		$("#editVideoId").val( type=="CALENDAR" ? id : videoId);
		$("#entityRowId").val(id);
		//添加类型（LABEL/VIDEO）
		$("#addType").val(addType);
	});
	$("#editImgDialog").dialog("open");
};

//删除前密码确认弹框
//@param delFn: 点击确认后执行删除的方法
//@param cancelFn: 点击取消后需要执行的回调方法
MZ.VideoUtil.initDelDialog = function( delFn, cancelFn ){
	$("body").append("<div id=\"delConfirmDialog\" style=\"display:none;\">"
			+ "<label>请输入密码：&nbsp;</label>"
			+ "<input type=\"password\" name=\"password\" id=\"password\"/>"
			+ "<input type=\"hidden\" id=\"deleteType\" name=\"deleteType\"/>"
			+ "<input type=\"hidden\" id=\"deleteId\" name=\"deleteId\"/></div>");
	
	$('#delConfirmDialog').dialog({  
        autoOpen:false, 
        resizable:false,
        height:120,
        width:350,  
        modal:true, 
        title:'密码确认',  
        overlay: { opacity: 0.5, background: "black" },  
        buttons:{
        	'确认':function(){
        		delFn && delFn.call(this);
        	},
	        '取消':function(){
	        	$(this).dialog("close");
	        	$("#password").val("");
	        	$("#deleteId").val("");
	        	$("#deleteType").val("");
	        	
	        	cancelFn && cancelFn.call(this);
	        }
        }
    });
};


/**
 * options
 * 
 * @param function
 *            loadChild 获取子节点数据函数,返回需要插入节点数组
 * @param string
 *            rowId 定义每行数据的id属性
 * @param string
 *            parId 定义每行数据的父id属性
 * @param string
 *            sortColumn 指定排序字段名称
 * @param string
 *            tableId 指定列表容器id
 * @param [function]
 *            bildColumns 定义生产各列数据的函数数组
 * @param boolean
 *            sortEdit 排序是否可编辑
 */

var TreeGrid = function(options) {
	this.settings = {};
	this.settings.sortEdit = true;

	$.extend(this.settings, options || {});
};

TreeGrid.prototype = {

	// 初始化，设置默认值，添加icon点击事件
	init : function(fn) {
		var _self = this;
		$(".toolbar.t-add, .toolbar.t-sub").live( "click", function() {
			_self.expand(this);
		});

		var tbl = this.settings.tableId;

		$("#" + tbl).on("focus", "input.sortEdit", function() {
			var reg = /^\+?[0-9][0-9]*$/;
			var val = $.trim($(this).val());
			val && reg.test(val) && $(this).attr("oval", val);
		}).on("blur", "input.sortEdit", function() {
			var oorder = $(this).attr("oval");
			var order = $.trim($(this).val()).replace(/^0+/g, "");
			var reg = /^\+?[0-9][0-9]*$/;
			var ele = this;
			if (!reg.test(order)) {
				jAlert("请输入正整数", "提示", function(){
					$(ele).val($(ele).attr("oval") || "1");
				});
				return false;
			} else {
				$(this).val(order);
			}

			if (oorder != order) {
				var sortRow = $(this).parent().parent().parent();
				_self.settings.saveSort(sortRow, order);
			}
		});

		this.settings.rowId = this.settings.rowId || "id";
		this.settings.parId = this.settings.parId || "parentId";
		this.settings.tableId = tbl || "tableList";
		this.settings.loadChild = this.settings.loadChild || function() {
		};
		this.settings.bildColumns = this.settings.bildColumns || [];

		this.reload(fn);
	},

	// 重新加载列表
	reload : function(fn) {
		var _self = this;
		this.settings.loadFirstData.call(this, function(data) {
			var htm = _self.buildHtml(data);
			$("#" + _self.settings.tableId).empty().append(htm);
			fn && fn.call();
		});
	},

	// 展开/合并 节点
	// @param expandIcon 展开/合并的图标对象
	expand : function(expandIcon) {
		var expandRow = $(expandIcon).parent().parent().parent();
		var id = $(expandRow).attr("id");
		var level = $(expandRow).attr("level");
		var parSort = $(expandRow).attr("sort");
		if (!id) {
			return;
		}

		if ($(expandIcon).hasClass("expland")) {
			$(expandIcon).removeClass("t-sub expland").addClass("t-add");
			this.removeChild(id);
		} else {
			var _self = this;
			_self.settings.loadChild(id, function(datas) {
				if (datas && datas.length > 0) {
					$(expandIcon).removeClass("t-add")
							.addClass("t-sub expland");
					$(expandRow).after(
							_self
									.buildHtml(datas, parseInt(level) + 1,
											parSort));
				} else {
					$(expandIcon).removeClass("t-add");
				}
			});
		}
	},

	// 生成一行数据的html
	// @param datas 数组集合，每个元素代表一行数据
	// @param level 展开等级
	// @param parSort 父节点的排序值
	buildHtml : function(datas, level, parSort) {
		level = level || 1;
		var sortStr = level > 1 ? (parSort + " - ") : "";
		var htm = [];
		for ( var i = 0, l = datas.length; i < l; i++) {
			var dat = datas[i];
			htm.push("<tr id=\"" + dat[this.settings.rowId] + "\"");
			htm.push(" parentId=\"" + dat[this.settings.parId] + "\"");
			htm.push(" sort = \"" + (sortStr + dat[this.settings.sortColumn])
					+ "\"");
			htm.push(" level = \"" + level + "\">");
			htm.push("<td align=\"left\" ><div style=\"width: "
					+ $(".hDivBox th:eq(0) div").width() + "px;\">"
					+ this.buildExpand(level, sortStr, dat[this.settings.isleaf]));
			var buildMethods = this.settings.bildColumns;
			for ( var j = 0, len = buildMethods.length; j < len; j++) {
				var result = buildMethods[j]["method"].call(this, dat);
				var align = buildMethods[j].align || "left";
				if (j > 0) {
					htm.push("<td align=\"left\"" 
							+ (j == len - 1 ? "" : (" title=\"" + (result+"").replace(/<.*>(.*)<\/.*>/, "$1") + "\"")));
					if (j == len - 1) {
						htm.push(" class = \"operation\" ");
					}
					htm.push("><div style=\"width:" + $(".hDivBox th:eq(" + j + ") div").width() + "px; text-align:" + align + "\">");
				}
				htm.push(result);
				htm.push("</div></td>");
			}

			htm.push("</tr>");
		}

		return htm.join("");
	},

	// 展开/合并 图标html
	// @param level 展开等级
	// @param sortStr 继承父节点的排序内容
	buildExpand : function(level, sortStr, isleaf) {
		var htm = [];
		htm.push("<a href='javascript:;' style='margin-left:");
		htm.push(level * 20);
		htm.push("px' class='toolbar");
		if(!isleaf){ // 叶子节点默认灰显
			htm.push(" t-add");
		}
		htm.push("'><span>&nbsp;</span></a>");
		htm.push(sortStr);
		return  htm.join("");
	},

	// 移除所有下级节点
	// @param id 父节点id
	removeChild : function(id) {
		var _self = this;
		$("[parentId" + "=" + id + "]").each(function() {
			var _id = $(this).attr("id");
			_self.removeChild(_id);
			$(this).remove();
		});
	},

	appendRow : function(row, parentId) {
	},
	updateRow : function(row) {
	},
	expandAll : function() {
	},
	collapseAll : function() {
	}
};


//列表排序
//options contains:
//1. sortList [{}]
//2. idCol string default[id]
//3. orderCol string default[order]
function OrderTool(){}

OrderTool.prototype = {
	orderList: [],
	idCol: "",
	orderCol: "",
	
	init: function(options){
		this.orderList = options.orderList || [];
		this.idCol = options.idCol || "id";
//		$.isArray(this.idCol) && (this.idCol = options.idCol.join("_"));
		
		this.orderCol = options.orderCol || "order";
		
		for ( var i = 0; i < this.orderList.length; i++ ) {
			this.orderList[i][this.orderCol] = i + 1;
		}
	},
	
	addItem: function(item){
		if ( !item ) {return;}
		
		item[this.orderCol] = this.orderList.length + 1;
		this.orderList.push(item);
	},
	
	removeItem: function(id){
		if ( !id ) {return;}
		
		var idx = -1;
		for ( var i = 0, l = this.orderList.length; i < l; i++ ) {
			var item = this.orderList[i];
			var key = [];
			if ($.isArray(this.idCol)) {
				for ( var m = 0, len = this.idCol.length; m < len; m++ ) {
					key.push(item[this.idCol[m]]);
				}
				key = key.join("_");
			} else {
				key = item[this.idCol];
			}
			if ( key == id ) {
				idx = i;
				break;
			}
		}
		if ( idx < 0 ) {return;}
		
		this.orderList.splice(idx, 1);
		
		for ( var i = idx, l = this.orderList.length; i < l; i++ ) {
			this.orderList[i][this.orderCol]--;
		}
	},
	
	addItems: function(items){
		if ( !$.isArray(items) ) {return;}
		
		for ( var i = 0, l = items.length; i < l; i++ ) {
			if ( !items[i] ) {continue;}
			
			items[i][this.orderCol] = this.orderList.length + 1;
			this.orderList.push(items[i]);
		}
	},
	
	clear: function(){
		this.orderList = [];
	},
	
	setOrder: function(item){
		var idx = this.findIdx(item);
		if ( idx == -1 ) {return;}
		
		var order = item[this.orderCol];
		if ( !order || order < 0 ) {
			return;
		}
		
		var oldOrder = this.orderList[idx][this.orderCol];
		if ( order > this.orderList.length ) {
			var old = this.orderList.splice(idx, 1)[0];
			for ( var i = idx, l = this.orderList.length; i < l; i++ ) {
				this.orderList[i][this.orderCol]--;
			}
			old[this.orderCol] = this.orderList.length + 1;
			this.orderList.push(old);
		} else {
			var old = this.orderList[idx];
			var place = this.orderList[order-1];
			
			old[this.orderCol] = order;
			place[this.orderCol] = oldOrder;
			
			this.orderList[idx] = place;
			this.orderList[order-1] = old;
		}
	},
	
	getOrder: function(item){
		if ( !item ) {return -1;}
		
		return this.findIdx(item) + 1;
	},
	
	findIdx: function(item){
		if ( !item ) {return -1;}
		
		var idVal = [];
		if ( $.isArray(this.idCol) ) {
			for ( var m = 0, len = this.idCol.length; m < len; m++ ) {
				idVal.push(item[this.idCol[m]]);
			}
			idVal = idVal.join("_");
		} else {
			idVal = item[this.idCol];
		}
		
		if ( !idVal ) {return -1;}
		
		var lis = this.orderList;
		for ( var i = 0, l = lis.length; i < l; i++ ) {
			var key = [];
			if ($.isArray(this.idCol)) {
				for ( var m = 0, len = this.idCol.length; m < len; m++ ) {
					key.push(lis[i][this.idCol[m]]);
				}
				key = key.join("_");
			} else {
				key = lis[i][this.idCol];
			}
			if ( idVal == key ) {
				return i;
			}
		}
		
		return -1;
	}
};

/**
 * 判断是否为正整数
 */
MZ.VideoUtil.isInt = function( num ){
	var reg = /^\+?[1-9][0-9]*$/;
	num = (num + "").replace(/^0+/g, "");
	return reg.test(num);
};

/**
 * 判断是否为非负整数(0和正整数)
 */
MZ.VideoUtil.isIntContainZreo = function( num ){
	var reg = new RegExp("^\\d+$");
	return reg.test(num);
};

/**
 * 输入框全选
 */
MZ.VideoUtil.initSelector = function (id){
	$("#"+id).bind("click",function(){
		$("#"+id).select();
	});
};

MZ.VideoUtil.errorCode = {
	invalidParam : 10000,
	missingParam : 10001,
	dbException : 10002,
	systemError : 5000
};

MZ.VideoUtil.handlerError =function(data){
			if(data.errorCode){
				switch(Number(data.errorCode)){
					case MZ.VideoUtil.errorCode.invalidParam :{
						if( $("#"+data.paramName).length > 0 ){
							ZZtips.attachTip(data.paramName,data.reason);
						}else{
							jAlert(data.reason,'提示');
						}
						return false;
						break;
					};
					case MZ.VideoUtil.errorCode.missingParam :{
						if( $("#"+data.paramName).length > 0 ){
							ZZtips.attachTip(data.paramName,data.reason);
						}else{
							jAlert(data.reason,'提示');
						}
						break;
					}
					case MZ.VideoUtil.errorCode.systemError :{
						jAlert("服务器繁忙，请稍后重试！",'提示');
						return false;
						break;
					}
					case MZ.VideoUtil.errorCode.dbException :{
						jAlert("服务器繁忙，请稍后重试！",'提示');
						console.error(data.reason);
						return false;
						break;
					}
				}
				
			}else{
				return true;
			}
		
};

jQuery.extend({
	getJsonExt : function(url,fn){
		$.getJSON(url,function(data){
			if(MZ.VideoUtil.handlerError(data)){
				fn(data);
			}
		});
	},
	postJsonExt : function(url,data,fn){
		$.postJSON(url,data,function(returnValue){
			if(MZ.VideoUtil.handlerError(returnValue)){
				fn(returnValue);
			}
		});
	}
});


MZ.VideoUtil.entranceAddTypeSelectChanged = function(){
     var type = $("#addType").getSelectedValue();
     var channelId = "channel"+$("#topChannelId").val();
     if(type=='label'){
    	 //clear data
       	 $("#addLabels").empty();
       	 $("#syncTypeSpan").empty();
    	 //获取标签列表数据
    	 MZ.VideoUtil.loadLabelOptions($("#addLabels"), 2, true, channelId);
    	 //获取同步方式数据
    	 var typeData = MZ.VideoResources.entranceSyncType;
    	 MZ.VideoUtil.loadSelectItem('syncTypeSpan',typeData,'syncType',typeData[0]);
    	 $("#addLabels").show();
    	 $("#syncTypeParent").show();
    	 $("#previewByLabelDiv").show();
    	 $("#previewByIdDiv").hide();
     }else if(type=='id'){
    	 $("#previewByIdSpan").empty();
    	 MZ.VideoUtil.loadSelectItem('previewByIdSpan',MZ.VideoResources.entranceSyncVideoType,'previewById',MZ.VideoResources.entranceSyncVideoType[0]);	 
    	 $("#syncTypeParent").hide();
    	 $("#addLabels").hide();
    	 $("#previewByLabelDiv").hide();
    	 $("#previewByIdDiv").show();
     }
};

MZ.VideoUtil.checkCpSource = function(video){
	var versionType = $("#versionType").val();
	if(video.status == 1 || video.status == "ENABLED"){
		//聚合版本
		if((video.cpSource == MZ.VideoResources.cpSource["TUDOU"] 
				|| video.cpSource == MZ.VideoResources.cpSource["YOUKU"] )
				&& versionType == MZ.VideoResources.VersionType["MULTI"]){
			jAlert("存在"+MZ.VideoResources.CategoryVersion[versionType]+"独家资源，不可保存！",'提示');
			return false;
		//土豆独家
		}else if(video.cpSource.indexOf(MZ.VideoResources.cpSource["TUDOU"])<0 
				&& versionType == MZ.VideoResources.VersionType["TUDOU"]){
			jAlert("存在非土豆资源，不可保存！",'提示');
			return false;
		}else if(video.cpSource.indexOf(MZ.VideoResources.cpSource["YOUKU"])<0
				&& versionType == MZ.VideoResources.VersionType["YOUKU"]){
			jAlert("存在非优酷资源，不可保存！",'提示');
			return false;
		}
	}
	return true;
};

MZ.VideoUtil.checkIsVipVideo = function(feeType,channelId){
	if($("#versionType").val() == MZ.VideoResources.VersionType['YOUKU']
		|| $("#versionType").val() == MZ.VideoResources.VersionType['TENCENT']){
		return true;
	}
	var parType = $("#parent_type").val();
	if(parType == "vip" || (channelId && parType == "top" && MZ.VideoResources.mzChannel['会员'] == channelId)){
		if(feeType != 2 && feeType != 3){
			jAlert('会员栏目下不能添加非会员内容！','提示');
			return false;
		}
	}else{
		if(feeType == 2 || feeType == 3){
			jAlert('非会员栏目下不能添加会员内容！','提示');
			return false;
		}
	}
	return true;
};

MZ.VideoUtil.toBusinessEdit = function(type,versionType){
	switch(type){
		case 'banner':{
			window.location.href = "/manage/bannerEntryCross/edit/";
		     break;
		}
		case 'feed':{
			window.location.href = "/manage/information/information-newsFeed?type="+type;
			break;
		}
	}
};

//页面显示视频列表时候使用
//初始小图片为固定图片，点击时弹框显示大图片。
MZ.VideoUtil.previewForInformation = function(containId){
	containId = containId || "mainList";
	$("body").append("<div id='showImgDialog' style='display: none'>" +
			"<img id='showImg' src='' alt='视频图片' width='400px;' height='255px;'/></div>");
	$('#showImgDialog').dialog({  
	  autoOpen:false, 
	  resizable:false,
	  height:380,
	  width:450,  
	  modal:true, 
	  title:'视频图片',  
	  overlay: { opacity: 0.5, background: "black" },  
	  buttons:{
	        '关闭':function(){
	        	$(this).dialog("close");
	        	$("#showImg").attr("src", "");
		        }
	      }
	  });
	$("#" + containId).on("click", "img[src='/resources/video/image/video.jpg']", function(){ 
		var obj = eval("("+$(this).attr("imgUrl")+")");
		$("#showImg").attr("src", obj.images);
		$("#showImgDialog").dialog("open");
	});
};


//图片编辑弹框
MZ.VideoUtil.initEditImgDialogForImformation = function(fn){
	$("body").append("<div style=\"display: none;\"  id=\"editImgDialog\">"
			+ "<input type=\"hidden\" id=\"editEntityId\" name=\"editEntityId\" value=\"\"/>"
			+ "<input type=\"hidden\" id=\"editOriginImg\" name=\"editOriginImg\" value=\"\"/>"
			+ "<input type=\"hidden\" id=\"videoType\" name=\"videoType\" value=\"\"/>"
			+ "<input type=\"hidden\" id=\"editId\" name=\"editId\" value=\"\"/>"
			+ "<div style=\"width: 385px;height: 160px;\">"
			+ "<img style=\"width: 385px;height: 160px;\" id=\"editImg\" src=\"\"/></div>"
			+ "<input type=\"text\" id=\"editImgUrl\" value=\"\" style=\"width: 385px;\"/>"
			+ "<input id=\"editImgUpload\" type=\"button\" class=\"Mbutton3\"  value=\"浏览\"/>"
			+ "<input id=\"resetImg\" type=\"button\" class=\"Mbutton3\" value=\"恢复原图\"/>"
			+ "<div><span>建议尺寸900*500以内，限JPG或PNG,500Kb以内</span></div></div>");
	
	$('#editImgDialog').dialog({  
        autoOpen:false, 
        resizable:false,
        height:380,
        width:450,  
        modal:true, 
        title:'编辑图片',  
        overlay: { opacity: 0.5, background: "black" },  
        buttons:{
        	'确认':function(){
        		var id = $("#editId").val();
        		if(id > 0){
        			var param = {
            			"id" : id,
            			"vid" : $("#editEntityId").val(),
            			"type" : $("#videoType").val(),
            			"images" : $("#editImgUrl").val(),
            			"position" : $("#position").val()
            		};
            		$.postJSON(MZ.VideoUtil.getUrl("/manage/information/editEntityImages"), param, function(data){
            			$("#editImgDialog").dialog("close");
            			if ( fn ) {
            				fn.call(this, data, $("#editEntityId").val(),$("#videoType").val());
            			}
            		});
        		}else{
        			$("#editImgDialog").dialog("close");
        			if ( fn ) {
        				fn.call(this, $("#editImgUrl").val(), $("#editEntityId").val(),$("#videoType").val());
        			}
        		}
        		
        	},
	        '返回':function(){$(this).dialog("close");}
        }
    });
	
	$("#resetImg").click(function(){
		if ( !$("#editOriginImg").val() ) {
			ZZtips.attachTip('resetImg','该视频无原图信息！');
		} else {
			if($("#editOriginImg").val() == $("#editImg").attr("src")){
				ZZtips.attachTip('resetImg','当前已为原图，无需恢复！');
			}else{
				$("#editImg").attr("src", $("#editOriginImg").val());
				$("#editImgUrl").val($("#editOriginImg").val());
			}
		}
	});
	
	$("#editImgUpload").uploadify({
        swf: "/resources/video/plugin/uploadify.swf", //flash文件的相对路径
        uploader: '/manage/upload/categoryImage', //后台处理程序的相对路径
        width: '80',
        height: '30',
        buttonClass: 'Mbutton3',
        fileObjName: '应用', //设置上传文件名称,默认为Filedata
        queueID: 'upload-progress', //文件队列的ID，该ID与存放文件队列的div的ID一致
        fileTypeDesc: 'png文件,jpg文件,gif文件', //用来设置选择文件对话框中的提示文本
        fileTypeExts: '*.png;*.jpg;*.gif;', //设置可以选择的文件的类型
        auto: true, //设置为true当选择文件后就直接上传了，为false需要点击上传按钮才上传
        multi: false, //设置为true时可以上传多个文件
        queueSizeLimit: 1,
        buttonText: '浏览', //浏览按钮的文本，默认值：BROWSE
        progressData: 'percentage', //上传队列显示的数据类型，percentage是百分比，speed是上传速度
        //回调函数
        onUploadError: function (errorObj) {
            if (errorObj.type === "File Size") {
                jAlert("上传的图标文件最大为2M", "提示");
                $(this).uploadifyClearQueue();
            }
        },
        onSelectError: function (queueSizeLimit) {
        	if (file.type && ![ ".png", ".jpg", ".gif" ].contains(file.type)) {
				jAlert("不支持 " + file.type + " 格式图片上传", "提示");
				return false;
			} else if (errorCode == -120) {
				jAlert("文件大小不能为0！", "提示");
				return false;
			}
        },
        onUploadSuccess: function (file, data) {
            var json = jQuery.parseJSON(data);
            if (json.error) {
				jAlert(json.error, "提示");
				return;
			}
            if (json[0].status == 200) {
                $("#editImgUrl").val(json[0].savedUrl);
                $("#editImg").attr('src',json[0].savedUrl);
            } else {
                jAlert("上传失败，请重试", "提示");
            }
        }
    });
};

/**
 * 编辑视频图片
 * @param addType 视频添加方式（LABEL:通过标签添加/VIDEO：通过ID添加 ）
 * @param type 实体类型（ALBUM/VIDEO） 
 */
MZ.VideoUtil.editInfoContentImg = function(id,videoId,type,images){
	var defaultImg = "/resources/video/image/video-default.png";
	if(id > 0){
		var url =  "/manage/information/reviewImages/"+id+"/"+type;
		$.postJSON(url, function(data){
			if(data){
				$("#editImg").attr("src",  data.images || defaultImg);
				$("#editImgUrl").val(data.images);
				$("#editOriginImg").val(data.oriImage || "");
			}else{
				$("#editImg").attr("src",  images || defaultImg);
				$("#editImgUrl").val(images);
			}
		});
	}else{
		$("#editImg").attr("src",  images || defaultImg);
		$("#editImgUrl").val(images);
	}
	$("#editId").val(id);
	$("#editImgUrl").attr("disabled","true");
	$("#videoType").val(type);
	$("#editEntityId").val(videoId);
	$("#editImgDialog").dialog("open");
};

MZ.VideoUtil.toggleInputText = function(flexiGrid,inputTextId,status){
	var obj = flexiGrid;
	 obj.find("tr td input").each(function(){
	     var allId = $(this).attr("id");
	     var id = '';
	     id = MZ.VideoUtil.removeBetweenASCII(allId,'0','9');
	     if(inputTextId == id){
	    	 $(this).attr("disabled",status);
	     }
	 });
};


MZ.VideoUtil.removeBetweenASCII = function(string,ascStart,ascEnd){
	var ret = '';
    for(var i=0;i<string.length;i++){
   	 var c = string.charAt(i);
   	 if(c<ascStart || c>ascEnd){
   		 ret+=c;
   	 }
    }
    return ret;
};

MZ.VideoUtil.isUndefined = function(params){
	if(typeof(param) == 'undefined'){
		return true;
	}
	return false;
};

MZ.VideoUtil.initVideoDetailCategoryType = function(){
	var type={
       "star" : "明星投票"
	};
	var hideType = MZ.VideoResources.videoDetailCategoryType[$("#hide_categoryType").val()];
	MZ.VideoUtil.loadSelectItem('categoryTypeSpan', type, 'categoryType', false,hideType==null?MZ.VideoResources.videoDetailCategoryType[1]:hideType);
	if (!$("#id") && $("#id").val() != "0" ) {
		$("#categoryType").attr("disabled", "disabled");
	}
};


MZ.VideoUtil.loadSelectItemVersionDelete = function(spanId, typeData, id, withAll, type) {
	var select = $(document.createElement("select"));
	if (withAll && !type) {
		select.append("<option value='-1' selected='selected'>全部</option>");
	}
	
	var vals = [];
	select.append("<option value='-1'>已添加明星</option");
	for (var i=0;i<typeData.length;i++) {
		if ( vals.contains(typeData[i].key) ) {
			continue;
		}
		vals.push(typeData[i].key);
		select.append("<option value='" + typeData[i].key + "'"
				+ '' + ">"
				+ typeData[i].value + "</option>");
	}
	select.attr('id', id);
	select.attr('name', id);
	$("#" + spanId).append(select);
};

MZ.VideoUtil.strStartWith = function(str,target){     
	  var reg=new RegExp("^"+target);     
	  return reg.test(str);        
};





